package com.nhc.activity_fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.nhc.database.dbmodel.WayTrail;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.model.TripItem;
import com.nhc.view.TripItemViewLayout;

import java.text.DecimalFormat;

import zuo.biao.library.base.BaseFragment;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.BottomMenuWindow;
import zuo.biao.library.ui.SelectColorActivity;
import zuo.biao.library.ui.SelectLineModeActivity;

public class NaviTrackInfoFragment extends BaseFragment implements View.OnClickListener, TimeRefresher.OnTimeRefreshListener {
    private final String TAG = "NaviTrackInfoFragment";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static NaviTrackInfoFragment createInstance() {
        return new NaviTrackInfoFragment();
    }
    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    private WayTrail wayTrailEdit = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.navitrackinfo_fragment);
        wayTrailEdit = DBDataCenter.getInstance().wayTrailEdit;

        if (DBDataCenter.getInstance().wayTrailThis != null
                && wayTrailEdit.getId() == DBDataCenter.getInstance().wayTrailThis.getId()) {
            isWayTrailThis = true;
        }

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        return view;//返回值必须为view
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private TripItemViewLayout navitrackinfoitem_0;
    private TripItemViewLayout navitrackinfoitem_1;
    private TripItemViewLayout navitrackinfoitem_2;
    private TripItemViewLayout navitrackinfoitem_3;
    private TripItemViewLayout navitrackinfoitem_4;
    private TripItemViewLayout navitrackinfoitem_5;
    private TripItemViewLayout navitrackinfoitem_6;
    private TripItemViewLayout navitrackinfoitem_7;
    private TripItemViewLayout navitrackinfoitem_8;
    private TripItemViewLayout navitrackinfoitem_9;

    private TextView tvTripItemContent;
    private ImageView ivIcon0;
    private View ivIcon1;
    private View ivIcon2;

    @Override
    public void initView() {//必须在onCreateView方法内调用
        navitrackinfoitem_0 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_0);
        navitrackinfoitem_1 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_1);
        navitrackinfoitem_2 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_2);
        navitrackinfoitem_3 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_3);
        navitrackinfoitem_4 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_4);
        navitrackinfoitem_5 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_5);
        navitrackinfoitem_6 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_6);
        navitrackinfoitem_7 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_7);
        navitrackinfoitem_8 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_8);
        navitrackinfoitem_9 = (TripItemViewLayout) findViewById(R.id.navitrackinfoitem_9);

        tvTripItemContent = (TextView) findViewById(R.id.tvTripItemContent);
        ivIcon0 = (ImageView) findViewById(R.id.iv_icon_0);
        ivIcon1 = (View) findViewById(R.id.iv_icon_1);
        ivIcon2 = (View) findViewById(R.id.iv_icon_2);
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initData() {//必须在onCreateView方法内调用
        refreshInfo();

        if (wayTrailEdit.getIsshow()) {
            ivIcon0.setImageResource(R.drawable.btn_open);
            tvTripItemContent.setText(R.string.ykq);
        } else {
            ivIcon0.setImageResource(R.drawable.btn_close);
            tvTripItemContent.setText(R.string.ygb);
        }

        drawColorCtrl();
        drawLineCtrl();
    }
    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    public void refreshInfo() {

        if (navitrackinfoitem_0 == null) {
            return;
        }

        if (isWayTrailThis) {
            wayTrailEdit.setEndtime(System.currentTimeMillis());

            long starttime = wayTrailEdit.getStarttime();
            long endtime = wayTrailEdit.getEndtime();

            int totaltime = (int) (endtime - starttime) / 1000;
            DecimalFormat DF = new DecimalFormat("00");
            int hour = totaltime / 3600;
            int min = (totaltime % 3600) / 60;
            int second = totaltime % 60;
            String strTime = DF.format(hour) + ":" + DF.format(min) + ":" + DF.format(second);
            navitrackinfoitem_0.bindView(new TripItem(getString(R.string.zsj), strTime, ""));

            if (wayTrailEdit.getNum() < 5000) {
                wayTrailEdit = DBDataCenter.getInstance().reUpdateWayTrail(wayTrailEdit);
            }
        } else {
            navitrackinfoitem_0.bindView(new TripItem(getString(R.string.zsj), Utils.getTimeDF(wayTrailEdit.getTotaltime()), ""));
        }

        navitrackinfoitem_1.bindView(new TripItem(getString(R.string.ydsj), Utils.getTimeDF(wayTrailEdit.getMovingtime()), ""));
        String DIS[] = SysUtils.getInstance().getDistanceStr((int) wayTrailEdit.getTrail_distance());
        navitrackinfoitem_2.bindView(new TripItem(getString(R.string.zjl), DIS[0], DIS[1]));
        String area[] = SysUtils.getInstance().getAreaStr(wayTrailEdit.getArea());
        navitrackinfoitem_3.bindView(new TripItem(getString(R.string.mj), area[0], area[1]));
        navitrackinfoitem_4.bindView(new TripItem(getString(R.string.point), wayTrailEdit.getNum() + "", "个"));
        String VEL[] = SysUtils.getInstance().getVelStr(wayTrailEdit.getAveragevel());
        navitrackinfoitem_5.bindView(new TripItem(getString(R.string.pjydsd), VEL[0], VEL[1]));

        String UP[] = SysUtils.getInstance().getAltitudeStr((int) wayTrailEdit.getUp());
        navitrackinfoitem_6.bindView(new TripItem(getString(R.string.zpsjl), UP[0], UP[1]));
        String DOWN[] = SysUtils.getInstance().getAltitudeStr((int) wayTrailEdit.getDown());
        navitrackinfoitem_7.bindView(new TripItem(getString(R.string.zxjjl), DOWN[0], DOWN[1]));
        String MIN[] = SysUtils.getInstance().getAltitudeStr(wayTrailEdit.getMinalt());
        navitrackinfoitem_8.bindView(new TripItem(getString(R.string.zdgd), MIN[0], MIN[1]));
        String MAX[] = SysUtils.getInstance().getAltitudeStr(wayTrailEdit.getMaxalt());
        navitrackinfoitem_9.bindView(new TripItem(getString(R.string.zggd), MAX[0], MAX[1]));
    }

    private boolean isWayTrailThis = false;//是否为当前航迹

    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用
        findViewById(R.id.navitrackinfo_ctrl_0).setOnClickListener(this);
        findViewById(R.id.navitrackinfo_ctrl_1).setOnClickListener(this);
        findViewById(R.id.navitrackinfo_ctrl_2).setOnClickListener(this);
    }

    public void doKeyUp() {
        setFoucseCtrl();
    }

    boolean _isFirst = true;

    private void setFoucseCtrl() {
        if (!_isFirst) {
            return;
        }

        _isFirst = false;
        for (int i = 0; i < CTRL_IDS.length; i++) {
            findViewById(CTRL_IDS[i]).setFocusable(true);
        }
        findViewById(R.id.navitrackinfo_ctrl_0).requestFocus();
    }

    private int[] CTRL_IDS = {
            R.id.navitrackinfo_ctrl_0, R.id.navitrackinfo_ctrl_1, R.id.navitrackinfo_ctrl_2};

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.navitrackinfo_ctrl_0:
                onWayTrailShow();
                break;
            case R.id.navitrackinfo_ctrl_1:
//                toActivity(BottomMenuWindow.createIntent(context, getResources().getStringArray(R.array.color_names))
//                        .putExtra(BottomMenuWindow.INTENT_TITLE, getString(R.string.xzhjys)), REQUEST_TO_BOTTOM_MENU_1, false);
                toActivity(SelectColorActivity.createIntent(context, wayTrailEdit.getColorstyle(), wayTrailEdit.getPathstyle()), SELECT_COLOR);
                break;
            case R.id.navitrackinfo_ctrl_2:
//                toActivity(BottomMenuWindow.createIntent(context, getResources().getStringArray(R.array.line_styles))
//                        .putExtra(BottomMenuWindow.INTENT_TITLE, getString(R.string.xzhjstyles)), REQUEST_TO_BOTTOM_MENU_2, false);
                toActivity(SelectLineModeActivity.createIntent(context, wayTrailEdit.getColorstyle(), wayTrailEdit.getPathstyle()), SELECT_LINEMODE);
                break;
            default:
                break;
        }
    }

    void onWayTrailShow() {
        boolean isshow = wayTrailEdit.getIsshow();
        isshow = !isshow;
        wayTrailEdit.setIsshow(isshow);

        if (isshow) {
            ivIcon0.setImageResource(R.drawable.btn_open);
            tvTripItemContent.setText(getString(R.string.ykq));
            showShortToast(getString(R.string.hjykqdtxs));
        } else {
            ivIcon0.setImageResource(R.drawable.btn_close);
            tvTripItemContent.setText(getString(R.string.ygb));
            showShortToast(getString(R.string.hjygbdtxs));
        }
    }

    private final int REQUEST_TO_BOTTOM_MENU_1 = 31;
    private final int REQUEST_TO_BOTTOM_MENU_2 = 32;

    private final int SELECT_COLOR = 33;
    private final int SELECT_LINEMODE = 34;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode != RESULT_OK) {
//            return;
//        }
        switch (requestCode) {
            case REQUEST_TO_BOTTOM_MENU_1:
                if (data != null) {
                    String[] COLOR_NAMES = getResources().getStringArray(R.array.color_names);
                    int selectedPosition = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (selectedPosition >= 0 && selectedPosition < COLOR_NAMES.length) {
                        wayTrailEdit.setColorstyle(selectedPosition);
                        drawLineCtrl();
                        drawColorCtrl();
                    }
                }
                break;
            case REQUEST_TO_BOTTOM_MENU_2:
                if (data != null) {
                    String[] LINE_STYLES = getResources().getStringArray(R.array.line_styles);
                    int selectedPosition = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (selectedPosition >= 0 && selectedPosition < LINE_STYLES.length) {
                        wayTrailEdit.setPathstyle(selectedPosition);
                        drawLineCtrl();
                    }
                }
                break;
            case SELECT_COLOR:
                wayTrailEdit.setColorstyle(resultCode);
                drawLineCtrl();
                drawColorCtrl();
                break;
            case SELECT_LINEMODE:
                wayTrailEdit.setPathstyle(resultCode);
                drawLineCtrl();
                break;
        }
    }

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    void drawLineCtrl() {
        int pathstyle = wayTrailEdit.getPathstyle();

        int width = Utils.dip2px(context, 105);
        int height = Utils.dip2px(context, 46);
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); //设置位图的宽高,bitmap为透明
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);//设置为透明，画布也是透明

        PathEffect pathEffect = null;
        switch (pathstyle) {
            default:
            case 0://实线
                pathEffect = new DashPathEffect(new float[]{5, 0}, 0);
                break;
            case 1://虚线1
                pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
                break;
            case 2://虚线2
                pathEffect = new DashPathEffect(new float[]{10, 10}, 1);
                break;
            case 3://虚线2
                pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
                break;
            case 4://虚线2
                pathEffect = new DashPathEffect(new float[]{20, 10}, 0);
                break;
            case 5://虚线2
                pathEffect = new DashPathEffect(new float[]{12, 8, 6, 4}, 0);
                break;
        }
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(6);
        paint.setColor(wayTrailEdit.getColor());
        paint.setAntiAlias(true);
        paint.setPathEffect(pathEffect);

        Path path = new Path();
        path.moveTo(0, height / 2);
        path.lineTo(width, height / 2);
        canvas.drawPath(path, paint);

        Drawable drawable = new BitmapDrawable(bitmap);
        ivIcon2.setBackgroundDrawable(drawable);
    }

    void drawColorCtrl() {
        int width = Utils.dip2px(context, 65);
        int height = Utils.dip2px(context, 46);
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); //设置位图的宽高,bitmap为透明
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);//设置为透明，画布也是透明

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(2);
        paint.setColor(wayTrailEdit.getColor());
        paint.setAntiAlias(true);

        canvas.drawCircle(width / 2, height / 2, height / 2 - 12, paint);
        Drawable drawable = new BitmapDrawable(bitmap);
        ivIcon1.setBackgroundDrawable(drawable);
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {
        refreshInfo();
    }

    @Override
    public void onTimerStop() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (isWayTrailThis && !wayTrailEdit.getIsPause()) {
            TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }


}